﻿using Org.BouncyCastle.Utilities.Encoders;
using PasswdTool;
using PasswdTool.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Runtime.Serialization;
using System.Text;

namespace Tables
{
    public class UserTable
    {
        private DataTable userData;
        public static UserTable SetUserData(DataTable dataTable)
        {
            UserTable userTable = new UserTable
            {
                userData = dataTable
            };
            return userTable;
        }
        public UserTable()
        {
            userData = new DataTable
            {
                TableName = "user"
            };
            var idColl = userData.Columns.Add("id", typeof(int));
            idColl.AutoIncrement = true;
            idColl.AutoIncrementSeed = 1;
            idColl.AutoIncrementStep = 1;
            var nameColl = userData.Columns.Add("name", typeof(string));
            nameColl.Unique = true;
            userData.Columns.Add("passwd", typeof(string));
            userData.Columns.Add("encrypt", typeof(string));
            userData.Columns.Add("iv", typeof(string));
            userData.Columns.Add("add_time", typeof(DateTime));
            userData.Columns.Add("update_time", typeof(DateTime));
        }

        public void Insert(UserModel model)
        {
            DataRow row = userData.NewRow();
            row["name"] = model.Name;
            row["passwd"] = model.Passwd;
            row["encrypt"] = Hex.ToHexString(model.Encrypt);
            row["iv"] = Hex.ToHexString(model.IV);
            row["add_time"] = DateTime.Now;
            row["update_time"] = DateTime.Now;
            userData.Rows.Add(row);
        }

        public int Remove(int id)
        {
            DataRow[] rows = userData.Select("id="+id);
            int count = rows.Length;
            foreach (var item in rows)
            {
                item.Delete();
            }
            return count;
        }
        public int Update(PasswdModel model)
        {
            DataRow[] rows = userData.Select("id=" + model.Id);
            int count = 0;
            for (int i = rows.Length - 1; i >= 0; i--)
            {
                bool isUpdate = false;
                if (!string.IsNullOrEmpty(model.Name) && model.Name.Equals(rows[i]["mame"]))
                {
                    rows[i]["name"] = model.Name;
                    isUpdate = true;
                }
                if (!string.IsNullOrEmpty(model.Passwd) && model.Passwd.Equals(rows[i]["passwd"]))
                {
                    rows[i]["passwd"] = model.Passwd;
                    isUpdate = true;
                }
                if (isUpdate)
                {
                    rows[i]["update_time"] = DateTime.Now;
                    count++;
                }
            }
            return count;
        }
        public List<UserModel> Query(UserModel model)
        {
            List<UserModel> result = new List<UserModel>();
            StringBuilder query = new StringBuilder();
            if (model.Id > 0)
            {
                query.Append("id=" + model.Id);
            }
            if (!string.IsNullOrEmpty(model.Name))
            {
                if (query.Length > 0)
                {
                    query.Append(" and ");
                }
                query.Append("name= '"+model.Name+"'");
            }
            if (!string.IsNullOrEmpty(model.Passwd))
            {
                if (query.Length > 0)
                {
                    query.Append(" and ");
                }
                query.Append("passwd= '" + model.Passwd + "'");
            }
            var rows = userData.Select(query.ToString(),"id DESC");
            foreach (var row in rows)
            {
                result.Add(new UserModel()
                {
                    Id = int.Parse(row["id"].ToString()),
                    Name = row["name"].ToString(),
                    Passwd = row["passwd"].ToString(),
                    Encrypt = Hex.Decode(row["encrypt"].ToString()),
                    IV = Hex.Decode(row["iv"].ToString()),
                });  
            }
            return result;
        }

        public void Serialize()
        {
            GlobalContainer.Serialize(GlobalContainer.userTable, userData);
        }

        public static UserTable Deserialize()
        {
            UserTable userTable = new UserTable
            {
                userData = GlobalContainer.Deserialize(GlobalContainer.userTable)
            };
            return userTable;
        }
    }
}
